package wqh.controller.file;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import wqh.domain.AlarmConfirm;
import wqh.global.GlobalSession;
import wqh.pojo.MapRet;
import wqh.pojo.xkLog;
import wqh.service.AlarmConfirmService;
import wqh.service.SystemLogService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * Created by devts on 2016/11/12.
 */

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/export/alarm")
public class AlarmLogExport {

    @Autowired
    private AlarmConfirmService alarmConfirmService;

    @Autowired
    private SystemLogService systemLogService;

    @RequestMapping(value = "/getAlarm",method = RequestMethod.GET)
    public Object get(HttpServletRequest request,
                                      HttpServletResponse response,
                                      @RequestParam(value = "start",required = true) int start,
                                      @RequestParam(value = "end",required = true) int end,
                                      @RequestParam(value = "type",required = false,defaultValue = "火警") String type)
    {
        try {
            String sessionID = request.getSession().getId();
            String userName = GlobalSession.getUserNameBySessionID(sessionID);
            if(userName == null) userName = "空用户";

            List<AlarmConfirm> alarmConfirmList = alarmConfirmService.findByTimeRangeAndType(type,start,end);
            if(alarmConfirmList.size() == 0) return MapRet.ERROR("该时间范围内没有记录");
            String[] columns = {"报警时间","报警区域","报警建筑物","报警楼层","报警主机名称","报警点名称","报警传感器类别","确认时间","确认用户"};
            HSSFWorkbook book = new HSSFWorkbook();
            HSSFSheet sheet = book.createSheet();
            sheet.addMergedRegion(new CellRangeAddress(0,0,0,columns.length - 1));
            HSSFRow headRow = sheet.createRow(0);
            HSSFCellStyle cellStyleTitle = book.createCellStyle();
            cellStyleTitle.setAlignment(CellStyle.ALIGN_CENTER);
            HSSFCell titleCell = headRow.createCell(0);
            titleCell.setCellValue(new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date((long)start * 1000)) + "至" +
                    new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date((long)end * 1000)) + type +"记录");
            titleCell.setCellStyle(cellStyleTitle);
            HSSFCell titleRightCell = headRow.createCell(columns.length - 1);
            titleRightCell.setCellStyle(cellStyleTitle);
            headRow = sheet.createRow(1);
            for(int i = 0; i < columns.length; i++){
                HSSFCell cell = headRow.createCell(i);
                cell.setCellValue(columns[i]);
            }
            sheet.setColumnWidth(0,38*120);
            sheet.setColumnWidth(1,38*80);
            sheet.setColumnWidth(2,38*80);
            sheet.setColumnWidth(3,38*50);
            sheet.setColumnWidth(4,38*120);
            sheet.setColumnWidth(5,38*80);
            sheet.setColumnWidth(6,38*120);
            sheet.setColumnWidth(7,38*120);
            sheet.setColumnWidth(8,38*50);
            for(int i = 2; i < alarmConfirmList.size() + 2; i++){
                AlarmConfirm a = alarmConfirmList.get(i - 2);
                HSSFRow nextRow = sheet.createRow(i);
                HSSFCell cell = nextRow.createCell(0);
                cell.setCellValue(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date((long)a.getAlarm_time() * 1000)));
                cell = nextRow.createCell(1);
                cell.setCellValue(a.getGeo_1_name());
                cell = nextRow.createCell(2);
                cell.setCellValue(a.getGeo_2_name());
                cell = nextRow.createCell(3);
                cell.setCellValue(a.getGeo_3_name());
                cell = nextRow.createCell(4);
                cell.setCellValue(a.getDevice_name());
                cell = nextRow.createCell(5);
                cell.setCellValue(a.getMonitor_name());
                cell = nextRow.createCell(6);
                cell.setCellValue(a.getSensor_name());
                cell = nextRow.createCell(7);
                cell.setCellValue(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date((long)a.getConfirm_time() * 1000)));
                cell = nextRow.createCell(8);
                cell.setCellValue(a.getUser());
            }
            String fileName = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date((long)start * 1000)) + "至" +
                    new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date((long)end * 1000)) + type +"记录.xls";
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            book.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName).getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            byte[] buff = new byte[4096];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();

            xkLog.addLog(systemLogService,"导出 " + fileName,xkLog.getFileConfig(),userName);

            return MapRet.FILE_DOWNLOAD_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            return MapRet.FILE_DOWNLOAD_ERROR();
        }
    }

}
